package com.caiheng.api.service.survey.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.event.EventPlanMapper;
import com.caiheng.api.dao.event.EventPlanTaskInfoMapper;
import com.caiheng.api.dao.event.EventPlanTaskMapper;
import com.caiheng.api.dao.event.EventPlanWorkMapper;
import com.caiheng.api.dao.survey.SurveyQuestionMapper;
import com.caiheng.api.dao.survey.SurveyUserRecordInfoMapper;
import com.caiheng.api.dao.survey.SurveyUserRecordMapper;
import com.caiheng.api.entity.event.EventPlan;
import com.caiheng.api.entity.event.EventPlanTask;
import com.caiheng.api.entity.event.EventPlanTaskInfo;
import com.caiheng.api.entity.event.EventPlanWork;
import com.caiheng.api.entity.survey.SurveyQuestion;
import com.caiheng.api.entity.survey.SurveyUserRecord;
import com.caiheng.api.entity.survey.SurveyUserRecordInfo;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.survey.SurveyUserRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 问卷调查的用户填报数据Service业务层处理
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Service
public class SurveyUserRecordServiceImpl extends BaseServiceImpl<SurveyUserRecordMapper, SurveyUserRecord> implements SurveyUserRecordService {

    @Resource
    private SurveyUserRecordMapper recordMapper;
    @Resource
    private SurveyUserRecordInfoMapper recordInfoMapper;
    @Resource
    private EventPlanTaskMapper planTaskMapper;
    @Resource
    private EventPlanMapper planMapper;
    @Resource
    private EventPlanTaskInfoMapper planTaskInfoMapper;
    @Resource
    private EventPlanWorkMapper planWorkMapper;
    @Resource
    private SurveyQuestionMapper questionMapper;

    @Override
    @Transactional
    public int addRecord(int surveyId, int task_id, int task_info_id, int target_id, int point_qr_id,int point_qr_info_id, User user, SysUser sysUser, String answer, double lng, double lat) {
        int ret = 0;
        try{
            SurveyUserRecord record = new SurveyUserRecord();
            record.setSurveyId(surveyId);
            record.setEventTaskId(task_id);
            record.setEventTaskInfoId(task_info_id);
            if(sysUser!= null && sysUser.getEstateId() != null){
                record.setPropertyId(user.getPropertyId());
                record.setEstateId(user.getEstateId());
            }else{
                record.setPropertyId(user.getPropertyId());
                record.setEstateId(user.getEstateId());
            }
            record.setUserId(user.getId());
            record.setNickName(user.getNickName());
            record.setPhoneNum(user.getPhoneNum());
            record.setCreateTime(new Date());
            record.setPointQrId(point_qr_id);
            record.setPointQrInfoId(point_qr_info_id);
            ret = recordMapper.insert(record);
            if(ret <= 0){
                throw new TransactionalException("recordMapper insert error");
            }

            if(task_info_id > 0){
                EventPlanTaskInfo taskInfo = planTaskInfoMapper.selectById(task_info_id);
                if(taskInfo != null){
                    EventPlanWork work = planWorkMapper.selectById(taskInfo.getEventWorkId());
                    if(work != null){
                        QueryWrapper<EventPlanTask> qwTask = new QueryWrapper<>();
                        qwTask.eq("work_id", work.getId());
                        qwTask.eq("worker_sys_user_id", sysUser.getUserId());
                        qwTask.last("limit 1");
                        EventPlanTask task = planTaskMapper.selectOne(qwTask);
                        if(task != null){
                            //任务执行状态 0 - 未执行  1 - 已完成  2 - 已逾期
                            taskInfo.setState(1);
                            taskInfo.setHandleTime(new Date());
                            taskInfo.setSysUserId(sysUser.getUserId());
                            taskInfo.setSysUserName(sysUser.getNickName());
                            taskInfo.setWxUserId(user.getId());
                            taskInfo.setLng(new BigDecimal(lng));
                            taskInfo.setLat(new BigDecimal(lat));
                            taskInfo.setEventTaskId(task.getId());
                            ret = planTaskInfoMapper.updateById(taskInfo);
                            if(ret <= 0){
                                throw new TransactionalException("planTaskMapper updateById error");
                            }

                            //完成方式  0 - 任意一人完成  1 - 每人完成一次 2 - 指定人员完成
                            if(work.getFinishType() == 0){
                                //当前任务的所有 人
//                                QueryWrapper<EventPlanTaskInfo> qwInfoTotal = new QueryWrapper<>();
//                                qwInfoTotal.eq("event_work_id", task.getWorkId());
//                                long countInfoTotal = planTaskInfoMapper.selectCount(qwInfoTotal);

                                //已完成的人数
                                QueryWrapper<EventPlanTaskInfo> qwInfoCount = new QueryWrapper<>();
                                qwInfoCount.eq("event_work_id", task.getWorkId());
//                            qwInfoCount.eq("target_id", task.getEventTargetId());
                                qwInfoCount.eq("state", 1);//任务执行状态 0 - 未执行  1 - 已完成  2 - 已逾期
                                long countFinishInfo = planTaskInfoMapper.selectCount(qwInfoCount);

                                //对比当前work 的  任务完成情况
                                QueryWrapper<EventPlanTaskInfo> qwInfoCountAll = new QueryWrapper<>();
                                qwInfoCountAll.eq("event_work_id", task.getWorkId());
                                qwInfoCountAll.ne("state", 3);  //排除掉已取消的
                                long countInfoAll = planTaskInfoMapper.selectCount(qwInfoCountAll);

                                // task 表的 状态处理
                                //只要有一个人完成  本任务就结束了
                                if(countFinishInfo >= countInfoAll){
                                    // 当前是任意一个人完成都行，只要是有一个人完成了 当前这个任务结束
                                    task.setState(2);
                                }else{
                                    task.setState(1);
                                }
                                task.setHandleTime(new Date());
                                ret = planTaskMapper.updateById(task);
                                if(ret <= 0){
                                    throw new TransactionalException("planTaskMapper updateById error");
                                }

                                //task 表的状态值  0 - 未处理 1 - 进行中   2 - 已完成  3 - 已超期  4 - 已取消
                                QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
                                qw.eq("work_id", task.getWorkId());
                                qw.eq("state", 2);
                                long count = planTaskMapper.selectCount(qw);
                                ////任务状态 0 - 未处理 1 - 进行中   2 - 已完成  3 - 已超期
                                if(count > 0){
                                    work.setState(2);
                                }else{
                                    work.setState(1);
                                }
                                work.setWorkerSysUserId(sysUser.getUserId());
                                work.setOpTime(new Date());

                                ret = planWorkMapper.updateById(work);
                                if(ret <= 0){
                                    throw new TransactionalException("planWorkMapper updateById error");
                                }
                            }else if(work.getFinishType() == 1 || work.getFinishType() == 2){

                                //当前任务的所有 人
                                QueryWrapper<EventPlanTaskInfo> qwInfoTotal = new QueryWrapper<>();
                                qwInfoTotal.eq("event_work_id", task.getWorkId());
                                qwInfoTotal.ne("state", 3);//排除掉已取消的
                                long countInfoTotal = planTaskInfoMapper.selectCount(qwInfoTotal);

                                //已完成的人数
                                QueryWrapper<EventPlanTaskInfo> qwInfoCount = new QueryWrapper<>();
                                qwInfoCount.eq("event_work_id", task.getWorkId());
                                qwInfoCount.eq("state", 1);//任务执行状态 0 - 未执行  1 - 已完成  2 - 已逾期
                                long countInfo = planTaskInfoMapper.selectCount(qwInfoCount);

                                // task 表的 状态处理
                                if(countInfoTotal >= countInfo){
                                    // 当前是任意一个人完成都行，只要是有一个人完成了 当前这个任务结束
                                    task.setState(2);
                                }else{
                                    task.setState(1);
                                }
                                task.setHandleTime(new Date());
                                ret = planTaskMapper.updateById(task);
                                if(ret <= 0){
                                    throw new TransactionalException("planTaskMapper updateById error");
                                }

                                //对比当前work 的  任务完成情况
                                QueryWrapper<EventPlanTask> qwTaskTotal = new QueryWrapper<>();
                                qwTaskTotal.eq("work_id", task.getWorkId());
                                qwTaskTotal.ne("state", 3);//  不包含取消的任务
                                long countTaskTotal = planTaskMapper.selectCount(qwTaskTotal);

                                QueryWrapper<EventPlanTask> qw = new QueryWrapper<>();
                                qw.eq("work_id", task.getWorkId());
                                qw.eq("state", 2);
                                long count = planTaskMapper.selectCount(qw);
                                ////任务状态 0 - 未处理 1 - 进行中   2 - 已完成  3 - 已超期
                                if(count >= countTaskTotal){
                                    work.setState(2);
                                }else{
                                    work.setState(1);
                                }
                                ret = planWorkMapper.updateById(work);
                                if(ret <= 0){
                                    throw new TransactionalException("planWorkMapper updateById error");
                                }

                            }

                            //判断 当前计划下的 任务是否都已完成
                            EventPlan eventPlan = planMapper.selectById(task.getEventPlanId());
                            if(eventPlan != null){
                                QueryWrapper<EventPlanTask> qwTaskAll = new QueryWrapper<>();
                                qwTaskAll.eq("event_plan_id", task.getEventPlanId());
                                qwTaskAll.ne("state", 3);
                                long taskAllCount = planTaskMapper.selectCount(qwTaskAll);

                                QueryWrapper<EventPlanTask> qwTaskCount = new QueryWrapper<>();
                                qwTaskCount.eq("event_plan_id", task.getEventPlanId());
                                qwTaskCount.eq("state", 2);
                                long taskCount = planTaskMapper.selectCount(qwTaskCount);

                                if(taskCount >= taskAllCount){
                                    //任务状态 0 - 未开始 1 - 进行中 2 - 已完成
                                    eventPlan.setState(2);//
                                }else{
                                    eventPlan.setState(1);
                                }
                                ret = planMapper.updateById(eventPlan);
                                if(ret <= 0){
                                    throw new TransactionalException("planMapper updateById error");
                                }
                            }
                        }
                    }
                }
            }

            Integer recordId = record.getId();
            JSONArray jsonArray = JSONUtil.parseArray(answer);
            for (int i = 0;i < jsonArray.size();i++){
                JSONObject jsonObject = (JSONObject)jsonArray.get(i);
                SurveyQuestion question = questionMapper.selectById(jsonObject.getInt("question_id"));
                if(question!= null){
                    //  这里只保存  输入型题 和 选择题，  上传图片的不处理
                    if(question.getQuestionType() < 2){

                        SurveyUserRecordInfo recordInfo = new SurveyUserRecordInfo();
                        recordInfo.setRecordId(recordId);
                        recordInfo.setUserId(user.getId());
                        recordInfo.setQuestionId(jsonObject.getInt("question_id"));
                        recordInfo.setIsImg(0);
                        if(jsonObject.getInt("question_type") == 0){
                            recordInfo.setAnswer(jsonObject.getInt("check_value").toString());
                        }else{
                            recordInfo.setAnswer(jsonObject.getStr("check_value"));
                        }
                        recordInfo.setCreateTime(new Date());
                        ret = recordInfoMapper.insert(recordInfo);
                        if(ret <= 0){
                            throw new TransactionalException("recordMapper insert error");
                        }
                    }
                }
            }
            ret = recordId;
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("addRecord insert error");
        }
        return ret;
    }
}
